package co.iiitb.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.iiitb.model.User_Login;
import com.iiitb.utils.MyLog;
import com.iiitb.utils.TMS_DB;

public class UserDAO {
	
	public static List<User_Login> getAllUsers() 
	{
		ArrayList<User_Login> selection = new ArrayList<User_Login>();
		ResultSet resultSet = null;
		String query = "select user_id,username,pswd,role " +
				"from user_login " ;
		Connection connection = TMS_DB.getConnection();
		resultSet = TMS_DB.readFromDB(query, connection);
		try {
			while (resultSet.next()) {
				User_Login usr = getUserFromResultSet(resultSet);
				selection.add(usr);
			}
		} catch (SQLException e) {
            MyLog.myCatch("UserDAO.java", 29, e);
			e.printStackTrace();
		}
		TMS_DB.close(resultSet);
		TMS_DB.close(connection);
		return selection;
	}
	
	public static User_Login getUserFromResultSet(ResultSet resultSet) {
		User_Login user= new User_Login();
		try 
		{
			user.setUserId(( resultSet.getInt("user_id")));
			user.setUsername(( resultSet.getString("username")) );
			user.setPassword(( resultSet.getString("pswd")));
			user.setRole((resultSet.getString("role")));
			return user;
		} 
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	public static User_Login findOne(String selectionModifier) {
		ResultSet resultSet = null;
		String query = "select user_id,username,pswd,role " +
				"from user_login " + selectionModifier;
		Connection connection = TMS_DB.getConnection();
		resultSet = TMS_DB.readFromDB(query, connection);
		try 
		{
			if (resultSet.next()) 
			{
				User_Login usr = getUserFromResultSet(resultSet);
				TMS_DB.close(resultSet);
				TMS_DB.close(connection);
				return usr;
			}
		} 
		catch (SQLException e) 
		{
            MyLog.myCatch("UserDAO.java", 72, e);
			e.printStackTrace();
		}
		TMS_DB.close(resultSet);
		TMS_DB.close(connection);
		return null;
	}
}
